package com.zhongyouyun.config;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import java.util.concurrent.TimeUnit;

@Component
public class RedisConfig {
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;


    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * 设置key-value到redis
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,Object value, Long time) {
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            if (ObjectUtil.isNotNull(time)) {
                this.redisTemplate.expire(key, time, TimeUnit.SECONDS);//设置分钟
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过key获取redis中的值
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 通过key获取redis中的值
     *
     * @param key
     * @return
     */
    public Object romove(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 获得锁
     *
     * @param lockId      锁ID
     * @param millisecond 时间，毫秒
     */

    public boolean getLock(String lockId, long millisecond) {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock",
                millisecond, TimeUnit.MILLISECONDS);
        return success != null && success;
    }

    /**
     * 释放锁
     *
     * @param lockId
     */
    public void releaseLock(String lockId) {
        redisTemplate.delete(lockId);
    }

}
